package com.googlecode.jmxlogger.model.output;

import org.jrobin.core.RrdDb;
import org.jrobin.core.RrdDef;
import org.jrobin.core.RrdDefTemplate;

import com.googlecode.jmxlogger.model.Query;
import com.googlecode.jmxlogger.util.BaseOutputWriter;

/**
 * This takes a JRobin template.xml file and then creates the database if it doesn't already exist.
 * 
 * It will then write the contents of the Query (the Results) to the database.
 * 
 * @author jon
 */
public class RRDWriter extends BaseOutputWriter {

    /** */
    public RRDWriter() {
    }

    /** */
    public void doWrite(Query query) throws Exception {
        RrdDb db = null;
        try {
            db = createOrOpenDatabase();
        } finally {
            db.close();
        }
    }

    /**
     * If the database file doesn't exist, it'll get created, otherwise, it'll be returned in r/w mode.
     */
    protected RrdDb createOrOpenDatabase() throws Exception {
        RrdDb result = null;
        if (!this.getOutputFile().exists()) {
            RrdDefTemplate t = new RrdDefTemplate(this.getTemplateFile());
            t.setVariable("database", this.getOutputFile().getCanonicalPath());
            RrdDef def = t.getRrdDef();
            result = new RrdDb(def);
        } else {
            result = new RrdDb(this.getOutputFile().getCanonicalPath());
        }
        return result;
    }
}
